﻿using System;
using Gadgeteer.Interfaces;
using Gadgeteer.Interfaces.Graphics;

namespace Gadgeteer.Interfaces.Sample.PhotoCamera.CameraApp
{
    public class CameraInteraction
    {
        private readonly BusyIndicationStack stack;
        private readonly ICamera camera;
        private readonly IGraphics graphics;
        private readonly ILogger logger;
        private BusyIndicator indicator = null;
        private readonly IButton button;

        public CameraInteraction(BusyIndicationStack stack, 
            ICamera camera, IGraphics graphics, IButton button, ILogger logger)
        {
            if (stack == null) throw new ArgumentNullException("stack");
            if (camera == null) throw new ArgumentNullException("camera");
            if (graphics == null) throw new ArgumentNullException("graphics");
            if (logger == null) throw new ArgumentNullException("logger");
            if (button == null) throw new ArgumentNullException("button");

            this.stack = stack;
            this.camera = camera;
            this.graphics = graphics;
            this.logger = logger;
            this.button = button;

            logger.Print("Camera interaction started.");
            graphics.Clear();

            button.ButtonReleased += button_ButtonReleased;
        }

        void button_ButtonReleased(IButton sender, ButtonState state)
        {
            TakePicture();
        }

        public void TakePicture()
        {
            logger.Print("Take picture called.");
            if (indicator == null)
            {
                indicator = stack.Get();
                camera.TakePicture();
                camera.PictureCaptured += camera_PictureCaptured;
            }
            else
            {
                logger.Print("Skipped taking picture because it was in progress.");
            }
        }

        void camera_PictureCaptured(ICamera sender, Gadgeteer.Picture picture)
        {
            logger.Print("Picture is taken, send to display.");
            camera.PictureCaptured -= camera_PictureCaptured;
            graphics.DisplayImage(picture, 5, 5);

            indicator.Dispose();
            indicator = null;
            logger.Print("Clearing empty.");
        }
    }
}
